package com.example.translateappjava.Activity.HomeFragmentActivity.Forum;

import android.app.Activity; // 需要导入 Activity
import android.content.Intent;
import android.os.Bundle;
import android.util.Log; // 需要导入 Log
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.translateappjava.R;
import com.example.translateappjava.Utils.Post; // 确保导入的是更新后的 Post 类

import java.time.Instant; // 需要导入 Instant
import java.util.ArrayList;
// import java.util.UUID; // 不再需要在这里生成UUID

public class ForumActivity extends AppCompatActivity implements ForumFragment.ForumListener {

    private ForumFragment forumFragment;
    private static final int CREATE_POST_REQUEST_CODE = 1001;
    private static final String TAG = "ForumActivity"; // 添加TAG

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forum);

        if (savedInstanceState == null) {
            initForumFragment();
        } else {
            forumFragment = (ForumFragment) getSupportFragmentManager().findFragmentByTag("ForumFragmentTag");
            if (forumFragment == null) {
                initForumFragment();
            }
        }
    }

    private void initForumFragment() {
        forumFragment = ForumFragment.newInstance();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment_container, forumFragment, "ForumFragmentTag");
        transaction.commit();
    }

    @Override
    public void onPostClick(Post post) {
        Intent intent = new Intent(this, PostDetailActivity.class);

        // 使用 getServerId() 获取帖子的服务器ID
        if (post.getServerId() != null) {
            // PostDetailActivity 应该期望接收一个 Long 类型的 post_id
            // 如果它期望 String，则需要 String.valueOf(post.getServerId())
            intent.putExtra("post_id", post.getServerId());
            Log.d(TAG, "Passing serverId to PostDetailActivity: " + post.getServerId());
        } else {
            // 如果 serverId 为 null (例如，帖子尚未成功上传并从服务器获取ID)
            // 你需要决定如何处理。可以不传递ID，或者传递一个特殊值。
            // 或者，如果PostDetailActivity也能处理基于localId的帖子，可以传递localId
            Log.w(TAG, "serverId is null for post titled '" + post.getTitle() + "'. Consider how PostDetailActivity handles this.");
            // intent.putExtra("post_id", post.getLocalId()); // 示例：传递localId作为备用
        }

        intent.putExtra("post_title", post.getTitle());
        intent.putExtra("post_content", post.getContent());
        intent.putExtra("post_username", post.getUsername());
        intent.putExtra("post_time", post.getTime());
        intent.putExtra("post_category", post.getCategory());
        intent.putExtra("post_like_count", post.getLikeCount());
        intent.putExtra("post_comment_count", post.getCommentCount());
        intent.putExtra("post_avatar_url", post.getAvatarUrl());
        startActivity(intent);
    }

    @Override
    public void onSearchClick(ArrayList<Post> allPosts) {
        Intent intent = new Intent(this, ForumSearchActivity.class);
        startActivity(intent);
    }

    @Override
    public void onAddPostClick() {
        Intent intent = new Intent(this, CreatePostActivity.class);
        startActivityForResult(intent, CREATE_POST_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CREATE_POST_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
            Post newPostFromServer = data.getParcelableExtra("newPost");
            if (newPostFromServer != null) {
                Log.d(TAG, "Received newPost from CreatePostActivity - ServerID: " + newPostFromServer.getServerId() +
                        ", Author: " + newPostFromServer.getUsername() +
                        ", Title: " + newPostFromServer.getTitle());

                // 确保时间戳是当前（如果服务器没有设置或返回）
                // CreatePostActivity 现在应该会返回带有服务器时间或客户端当前时间的 Post
                if (newPostFromServer.getTime() == null || newPostFromServer.getTime().isEmpty()) {
                    newPostFromServer.setTime(Instant.now().toString());
                    Log.w(TAG, "Time was null for new post, set to current UTC time.");
                }

                // localId 会在存入Room时自动生成，serverId 已经从服务器获取
                // username 和 avatarUrl 应该由 CreatePostActivity 设置或从服务器返回时确认

                if (forumFragment != null) {
                    forumFragment.addPostToList(newPostFromServer); // 传递包含服务器ID的Post对象
                    Toast.makeText(this, "帖子已发布，正在刷新列表...", Toast.LENGTH_SHORT).show();
                }
            } else {
                Log.e(TAG, "newPost from CreatePostActivity is null, though result was OK.");
                Toast.makeText(this, "未能获取新帖子数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // onResume 和 refreshForumData 可以保持不变，它们通常触发 ForumFragment 的 refreshData
    @Override
    protected void onResume() {
        super.onResume();
        // if (forumFragment != null) {
        //    forumFragment.refreshData(); // 考虑是否需要在每次onResume时都刷新
        // }
    }

    public void refreshForumData() {
        if (forumFragment != null) {
            forumFragment.refreshData();
        }
    }
}